#!/usr/bin/env python3
"""
部署和测试脚本
"""

import os
import sys
import subprocess
import webbrowser
import time
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    if version.major < 3 or (version.major == 3 and version.minor < 7):
        print("❌ Python版本过低，需要Python 3.7+")
        return False
    print(f"✅ Python版本: {version.major}.{version.minor}.{version.micro}")
    return True

def check_dependencies():
    """检查依赖包"""
    required_packages = [
        'flask', 'pandas', 'numpy', 'matplotlib', 'openpyxl'
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package)
            print(f"✅ {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"❌ {package}")
    
    if missing_packages:
        print(f"\n缺少依赖包: {', '.join(missing_packages)}")
        print("正在安装...")
        try:
            subprocess.check_call([
                sys.executable, '-m', 'pip', 'install'
            ] + missing_packages)
            print("✅ 依赖包安装完成")
            return True
        except subprocess.CalledProcessError:
            print("❌ 依赖包安装失败")
            return False
    
    return True

def check_files():
    """检查必要文件"""
    required_files = [
        'app.py',
        'run.py',
        'templates/index.html',
        'static/js/main.js',
        'requirements.txt'
    ]
    
    missing_files = []
    for file_path in required_files:
        if not Path(file_path).exists():
            missing_files.append(file_path)
            print(f"❌ {file_path}")
        else:
            print(f"✅ {file_path}")
    
    if missing_files:
        print(f"\n缺少文件: {', '.join(missing_files)}")
        return False
    
    return True

def create_directories():
    """创建必要目录"""
    directories = ['data', 'static', 'static/js', 'templates']
    
    for directory in directories:
        Path(directory).mkdir(parents=True, exist_ok=True)
        print(f"✅ 目录: {directory}")
    
    return True

def run_tests():
    """运行测试"""
    print("\n" + "="*50)
    print("运行功能测试")
    print("="*50)
    
    try:
        result = subprocess.run([
            sys.executable, 'test_calculations.py'
        ], capture_output=True, text=True, timeout=60)
        
        if result.returncode == 0:
            print("✅ 功能测试通过")
            return True
        else:
            print("❌ 功能测试失败")
            print(result.stdout)
            print(result.stderr)
            return False
    except subprocess.TimeoutExpired:
        print("❌ 测试超时")
        return False
    except FileNotFoundError:
        print("❌ 测试文件不存在")
        return False

def create_sample_data():
    """创建示例数据"""
    print("\n" + "="*50)
    print("创建示例数据")
    print("="*50)
    
    try:
        subprocess.check_call([sys.executable, 'create_sample_data.py'])
        print("✅ 示例数据创建完成")
        return True
    except subprocess.CalledProcessError:
        print("❌ 示例数据创建失败")
        return False
    except FileNotFoundError:
        print("❌ 示例数据脚本不存在")
        return False

def start_server():
    """启动服务器"""
    print("\n" + "="*50)
    print("启动Web服务器")
    print("="*50)
    
    try:
        # 启动服务器
        print("正在启动服务器...")
        process = subprocess.Popen([
            sys.executable, 'run.py'
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        # 等待服务器启动
        time.sleep(3)
        
        # 检查服务器是否正在运行
        if process.poll() is None:
            print("✅ 服务器启动成功")
            print("🌐 访问地址: http://localhost:5000")
            
            # 自动打开浏览器
            try:
                webbrowser.open('http://localhost:5000')
                print("✅ 浏览器已打开")
            except:
                print("⚠️  请手动打开浏览器访问 http://localhost:5000")
            
            return process
        else:
            stdout, stderr = process.communicate()
            print("❌ 服务器启动失败")
            print(f"输出: {stdout.decode()}")
            print(f"错误: {stderr.decode()}")
            return None
            
    except Exception as e:
        print(f"❌ 启动服务器时发生错误: {e}")
        return None

def main():
    """主函数"""
    print("莫尔圆包络线计算系统 - 部署脚本")
    print("="*60)
    
    # 检查系统环境
    print("\n1. 检查系统环境")
    print("-" * 30)
    if not check_python_version():
        return False
    
    # 检查依赖
    print("\n2. 检查依赖包")
    print("-" * 30)
    if not check_dependencies():
        return False
    
    # 检查文件
    print("\n3. 检查项目文件")
    print("-" * 30)
    if not check_files():
        return False
    
    # 创建目录
    print("\n4. 创建必要目录")
    print("-" * 30)
    if not create_directories():
        return False
    
    # 创建示例数据
    if Path('create_sample_data.py').exists():
        if not create_sample_data():
            print("⚠️  示例数据创建失败，但不影响主要功能")
    
    # 运行测试
    if Path('test_calculations.py').exists():
        if not run_tests():
            print("⚠️  功能测试失败，但仍可以启动服务器")
    
    # 启动服务器
    server_process = start_server()
    
    if server_process:
        print("\n" + "="*60)
        print("🎉 部署完成！")
        print("="*60)
        print("📖 使用说明:")
        print("   1. 在浏览器中访问 http://localhost:5000")
        print("   2. 按照界面提示进行操作")
        print("   3. 可以使用data/目录下的示例文件测试")
        print("   4. 按 Ctrl+C 停止服务器")
        print("="*60)
        
        try:
            # 等待用户中断
            server_process.wait()
        except KeyboardInterrupt:
            print("\n正在停止服务器...")
            server_process.terminate()
            server_process.wait()
            print("✅ 服务器已停止")
        
        return True
    else:
        print("\n❌ 部署失败")
        return False

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
